package com.aaa.arouterone.testOcr

import android.R
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.*
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import java.lang.ref.WeakReference
import java.util.*

/**
 * 等待弹框
 */
class LoadingDialog : DialogFragment() {
    private var msg = "正在加载"
    private var onTouchOutside = true
    private var textView: TextView? = null


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Objects.requireNonNull(
            Objects.requireNonNull(
                dialog
            )?.window
        )?.setBackgroundDrawableResource(R.color.transparent)
        dialog!!.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog!!.setCanceledOnTouchOutside(onTouchOutside)
        val loadingView =
            inflater.inflate(com.aaa.arouterone.R.layout.dialog_loading, container)
        textView =
            loadingView.findViewById(com.aaa.arouterone.R.id.textView)
        textView?.setText(msg)
        return loadingView
    }

    fun setMsg(msg: String?): LoadingDialog {
        this.msg = msg.toString()
        if (textView != null) {
            textView!!.text = msg
        }
        return this
    }

    fun setOnTouchOutside(onTouchOutside: Boolean): LoadingDialog {
        this.onTouchOutside = onTouchOutside
        if (dialog != null) {
            dialog!!.setCanceledOnTouchOutside(onTouchOutside)
        }
        return this
    }

    override fun show(
        manager: FragmentManager,
        tag: String?
    ) {
        val mClass = DialogFragment::class.java
        val dismissed = mClass.getDeclaredField("mDismissed")
        dismissed.isAccessible = true
        dismissed.set(this, false)

        val shownByMe = mClass.getDeclaredField("mShownByMe")
        shownByMe.isAccessible = true
        shownByMe.set(this, true)
        val ft = manager?.beginTransaction()
        ft?.add(this, tag)
        ft?.commitAllowingStateLoss()
    }
}